package com.feign.request.impl;

import com.alibaba.fastjson.JSONObject;
import com.config.exception.BusinessException;
import com.feign.DynamicFeignClient;
import com.feign.request.RequestClient;
import feign.*;
import feign.codec.Decoder;
import feign.codec.Encoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.FeignClientsConfiguration;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Service;

import java.net.URI;
import java.net.URISyntaxException;

/**
 * @author Fang Ruichuan
 * @date 2022-10-09 11:10
 */
@Service
@Slf4j
@Import(FeignClientsConfiguration.class)
public class RequestClientImpl implements RequestClient {

    private DynamicFeignClient client;

    @Autowired
    public RequestClientImpl(Decoder decoder, Encoder encoder) {
        client = Feign.builder()
                .decoder(decoder)
                .encoder(encoder)
                .options(new Request.Options(1000, 1000))
                .logLevel(Logger.Level.FULL)
                .target(Target.EmptyTarget.create(DynamicFeignClient.class));
    }

    @Override
    public String sendPost(String url, JSONObject request) {
        log.info("url:{},入参:{}", url, request);
        String response;
        try {
            response = client.requestPOST(new URI(url), request);
        } catch (FeignException feignException) {
            throw new BusinessException("调用接口异常!地址:" + url);
        } catch (URISyntaxException uriSyntaxException) {
            throw new BusinessException("调用地址异常!地址:" + url);
        }
        log.info("url:{},出参:{}", url, response);
        return response;
    }
}
